#include "List.h"
#include <stdlib.h>
#include <stdio.h>

int list_add(List_t* list, value_t val)
{
    List_t* new_val = (List_t*)malloc(sizeof(List_t));
    if (new_val == NULL)
        return -1;
    new_val->value = val;
    new_val->next = NULL;
    List_t* p = list;
    while (p->next!=NULL) 
        p = p->next;
    p->next = new_val;
    return 0;
}

int list_del(List_t* list, int id)
{
    List_t* p = list;
    List_t* pre_p;
    while (p->next != NULL) {
        pre_p = p;
        p = p->next;
        if (p->value.id == id) {
            pre_p->next = p->next;
            free(p);
            return 0;
        }
    }
    printf("there is no merchandise's id match %03d\n", id);
    return -1;
}

int list_modify(List_t* list, int id, value_t new_val)
{
    List_t* p = list;
    int i = 0;
    while (p != NULL) {
        p = p->next;
        i++;
        if (i == id) {
            p->value = new_val;
            return 0;
        }
    }
    printf("there is no merchandise's id match %03d\n", id);
    return -1;
}

int list_search(List_t* list, search_fun_t func, void* pattern, value_t* val)
{
    List_t* p = list;
    int index = 0;
    while (p != NULL) {
        if (func(p->value, pattern) == 0) {
            if (val != NULL)
                *val = p->value;
            return index;
        }
        p = p->next;
        index++;
    }
    printf("there is no merchandise's info match\n");
    return -1;
}

int list_traverse(List_t* list, value_t* val, int op)
{
    static int last_id = 1;
    List_t* val_p = list;
    int point = 0;
    while (point < last_id) {
        point++;
        val_p = val_p->next;
    }
    if (val_p != NULL){
        *val = val_p->value;
        last_id++;
        return 0;
    }
    else 
        last_id = 1;
    return -1;
}

int list_update(List_t* list, int index, value_t new_val)
{
    List_t* p = list;
    while (p != NULL && index > 0) {
        p = p->next;
        index--;
    }
    if (index == 0) {
        p->value = new_val;
        return 0;
    }
    else {
        puts("target not found!");
        return -1;
    }    
}